import 'package:cim_flutter_sdk/CimSocket.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:cim_flutter_sdk/cim_flutter_sdk.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String Message = 'Unknown';
  final _cimFlutterSdkPlugin = CimFlutterSdk();

  @override
  void initState() {
    super.initState();
    initCimState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initCimState() async {
    CIMSocket cimSocket;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      cimSocket = await _cimFlutterSdkPlugin.connect(
          '127.0.0.1', 23456, 16501516154949);
      cimSocket.addListener(() {
        print(cimSocket.model!.toProto3Json());
        if (!mounted) return;

        setState(() {
          Message = cimSocket.model!.toProto3Json().toString();
        });
      });
    } on PlatformException {}

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Text('Message is: $Message\n'),
        ),
      ),
    );
  }
}
